'use strict';

import $config from '../config/config.js'
/*
  util工具库
*/
class Util {
	constructor(arg) {}

	/**
	 * @description 日期格式化
	 */
	format(date, fmt) {
		if (!date) {
			return '';
		}
		if (typeof date === 'string') {
			date = date.replace(/\.|\-/g, '/');
		}
		if (typeof date !== 'object') {
			date = new Date(date);
		}

		fmt = fmt || 'yyyy-MM-dd hh:mm:ss'
		let o = {
			"M+": date.getMonth() + 1, //月份   
			"d+": date.getDate(), //日   
			"h+": date.getHours(), //小时   
			"m+": date.getMinutes(), //分   
			"s+": date.getSeconds(), //秒
			"q+": Math.floor((date.getMonth() + 3) / 3), //季度
			"S": date.getMilliseconds() //毫秒
		};
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (let k in o)
			if (new RegExp("(" + k + ")").test(fmt))
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
					.length)));
		return fmt;
	}
	formatDate(date, type, split) {
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		console.log(date)
		switch (type) {
			case 'month':
				return [year, month].map(this.formatNumber).join(split)
				break;
			case 'day':
				return [year, month, day].map(this.formatNumber).join(split)
				break;
			default:
				return [year, month, day].map(this.formatNumber).join(split)
				break;
		}
	}
	// --根据日期获取当月的开始结束日期
	getMonthRange(monthStr) {
		var monthArr = monthStr.split('-'); // 将传入的月份字符串按照"-"进行分割
		var year = parseInt(monthArr[0]); // 年份
		var month = parseInt(monthArr[1]); // 月份
		var startDate = new Date(year, month - 1, 1); // 当前月的第一天
		var endDate = new Date(year, month, 0); // 当前月的最后一天
		return {
			start: `${year}-${month.toString().padStart(2, '0')}-01`, // 拼接成年月日格式的字符串，返回当前月的第一天
			end: `${year}-${month.toString().padStart(2, '0')}-${endDate.getDate().toString().padStart(2, '0')}`, // 拼接成年月日格式的字符串，返回当前月的最后一天
			month: monthStr
		};
	}
	formatMonthDate(date, type, split) {
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		console.log(date)
		switch (type) {
			case 'month':
				return [year, month].map(this.formatNumber).join(split)
				break;
			case 'day':
				return [year, month, day].map(this.formatNumber).join(split)
				break;
			default:
				return [year, month, day].map(this.formatNumber).join(split)
				break;
		}
	}
	// 获取本周的开始结束日期
	getThisWeek() {
		console.log('获取本周的开始结束日期');
		let nowData = new Date();
		// 获取今天的是周几
		let currentMonth = nowData.getMonth();
		let currentDay = nowData.getDay();
		// 把currentDay == 0赋值给周日
		if (currentDay === 0) {
			currentDay = 7;
		}
		// 获取周一的时间戳
		let start = nowData.getTime() - (currentDay - 1) * 24 * 60 * 60 * 1000;

		// 获取周日的时间戳
		let end = nowData.getTime() + (7 - currentDay) * 24 * 60 * 60 * 1000;
		return {
			start: this.format(start, 'yyyy-MM-dd'),
			end: this.formatDate(nowData, 'day', '-'), // this.format(end, 'yyyy-MM-dd'),
			month: this.format(start, 'yyyy-MM')
		};
	}
	// 获取上周的开始结束日期
	getLastWeek() {
		console.log('获取上周的开始结束日期');
		let nowData = new Date();
		// 获取今天的是周几
		let currentMonth = nowData.getMonth();
		let currentDay = nowData.getDay();
		// 把currentDay == 0赋值给周日
		if (currentDay === 0) {
			currentDay = 7;
		}
		// 获取上周一的时间戳
		let start = nowData.getTime() - (currentDay + 6) * 24 * 60 * 60 * 1000;

		// 获取上周日的时间戳
		let end = nowData.getTime() - currentDay * 24 * 60 * 60 * 1000;
		return {
			start: this.format(start, 'yyyy-MM-dd'),
			end: this.format(end, 'yyyy-MM-dd'),
			month: this.format(start, 'yyyy-MM')
		};
	}
	// 获取下周的开始结束日期
	getNextWeek() {

	}
	// 获取本月的开始结束日期
	getThisMonth() {
		console.log('获取本月的开始结束日期');
		let nowData = new Date();
		// 获取今天所在的月份
		let currentMonth = nowData.getMonth();
		// 获得当前年份4位年
		let currentYear = nowData.getFullYear();
		// 本月的开始时间
		let start = new Date(currentYear, currentMonth, 1);
		// 本月的结束时间
		let end = new Date(currentYear, currentMonth + 1, 0);
		return {
			start: this.format(start, 'yyyy-MM-dd'),
			end: this.formatDate(nowData, 'day', '-'),
			_end: this.format(end, 'yyyy-MM-dd'),
			month: this.format(start, 'yyyy-MM')
		};
	}
	// 获取上月的开始结束日期
	getLastMonth() {
		console.log('获取上月的开始结束日期');
		let nowData = new Date();
		// 获取今天所在的月份
		let currentMonth = nowData.getMonth();
		// 获得当前年份4位年
		let currentYear = nowData.getFullYear();
		// 上个月的开始时间
		let start = new Date(currentYear, currentMonth - 1, 1);
		// 上个月的结束时间
		let end = new Date(currentYear, currentMonth, 0);
		console.log(currentMonth)
		return {
			start: this.format(start, 'yyyy-MM-dd'),
			end: this.format(end, 'yyyy-MM-dd'),
			month: this.format(start, 'yyyy-MM')
		};
	}
	// 获取本月为第几季度
	getQuarter() {
		let today = new Date();
		let month = today.getMonth() + 1;
		return Math.ceil(month / 3); // 当前8月份 值为：3
	}
	// 获取本季度的开始与结束日期
	getThisQuarter() {
		let today = new Date();
		let year = today.getFullYear();
		let quarter = this.getQuarter();
		let startDate, endDate;
		if (quarter == 1) {
			startDate = new Date(year, 0, 1);
			endDate = new Date(year, 2, 31);
		} else if (quarter == 2) {
			startDate = new Date(year, 3, 1);
			endDate = new Date(year, 5, 30);
		} else if (quarter == 3) {
			startDate = new Date(year, 6, 1);
			endDate = new Date(year, 8, 30);
		} else if (quarter == 4) {
			startDate = new Date(year, 9, 1);
			endDate = new Date(year, 11, 31);
		}
		return {
			startDate: startDate.toLocaleDateString(), // 2023/7/1
			endDate: endDate.toLocaleDateString() // 2023/9/30
		};
	}
	formatNumber(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}
	formatRandom() {
		let code = ''
		for (var i = 0; i < 6; i++) {
			code += parseInt(Math.random() * 10)
		}
		return code
	}
	// 分钟数转换为 小时：分钟 
	ChangeHourMinutestr(str) {
		if (str !== "0" && str !== "" && str !== null) {
			return ((Math.floor(str / 60)).toString().length < 2 ? (Math.floor(str / 60)).toString() :
				(Math.floor(str / 60)).toString()) + "小时" + ((str % 60).toString().length < 2 ? (str % 60)
				.toString() : (str % 60).toString()) + "分钟";
		} else {
			return "";
		}
	}
	// 小时分钟格式转换为分钟数
	ChangeStrToMinutes(str) {
		var arrminutes = str.split(":");
		if (arrminutes.length == 2) {
			var minutes = parseInt(arrminutes[0]) * 60 + parseInt(arrminutes[1]);
			return minutes;
		} else {
			return 0;
		}
	}

	format_price(_number, _sep) {
		_number = typeof _number != "undefined" && _number > 0 ? _number + '' : "";
		if (_number.indexOf('.') != -1) {
			_number = _number.split('.')[0];
		}
		_number = _number.replace(new RegExp("^(\\d{" + (_number.length % 3 ? _number.length % 3 : 0) +
				"})(\\d{3})", "g"),
			"$1 $2").replace(/(\d{3})+?/gi, "$1 ").trim()
		if (typeof _sep != "undefined" && _sep != " ") {
			_number = _number.replace(/\s/g, _sep);
		}
		return _number;
	}

	get_price_decimal(_price) {
		_price = _price + '';

		if (_price.indexOf('.') != -1) {
			return '.' + _price.split('.')[1];
		} else {
			_price = Math.random(2).toFixed(2);
		}

		return this.get_price_decimal(_price);
	}
	//--基于时间生成的随机订单号，具有唯一性
	setTimeDateFmt(s) { // 个位数补齐十位数
		return s < 10 ? '0' + s : s;
	}

	createordernum(type) {
		const now = new Date()
		let month = now.getMonth() + 1
		let day = now.getDate()
		let hour = now.getHours()
		let minutes = now.getMinutes()
		let seconds = now.getSeconds()
		month = this.setTimeDateFmt(month)
		day = this.setTimeDateFmt(day)
		hour = this.setTimeDateFmt(hour)
		minutes = this.setTimeDateFmt(minutes)
		seconds = this.setTimeDateFmt(seconds)
		let orderCode = type + "_test_" + now.getFullYear().toString() + month.toString() + day + hour + minutes +
			seconds + (Math.round(
				Math.random() * 1000000)).toString();
		return orderCode;
		//基于年月日时分秒+随机数生成订单编号
	}
	// 计算时间差
	getTimeDifference(order_expire_time) {
		var date2 = new Date(); //结束时间
		var date3 = new Date(order_expire_time).getTime() - date2.getTime(); //时间差的毫秒数  
		console.log(date3);
		//计算出小时数
		var leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
		var hours = Math.floor(leave1 / (3600 * 1000));
		//计算相差分钟数
		var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
		var minutes = Math.floor(leave2 / (60 * 1000));
		console.log(minutes);
		//计算相差秒数
		var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
		var seconds = Math.round(leave3 / 1000);
		return date3;
	}

	// 获取某个时间点距离现在的小时和分钟
	getTimeDiff(targetTime) {
		const currentTime = new Date();
		const diff = Math.abs(currentTime - targetTime);

		// 计算天、小时和分钟
		const days = Math.floor(diff / (1000 * 60 * 60 * 24));
		const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
		const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

		return {
			days,
			hours,
			minutes
		};
	}
	getPrice(price, TaxRate, priceTaxMark) {
		if (priceTaxMark == 1) {
			return price.ToString();
		} else {
			return price / (1 + TaxRate);
		}
		return "0";
	}
	/**
	 * @description 数值格式化
	 */
	format_number(number) {
		try {
			number = parseFloat(number);

			if (number > 10000 * 1000) {
				return (number / (10000 * 10000)).toFixed(1) + '亿';
			}

			if (number > 10000) {
				return (number / (10000 * 1)).toFixed(1) + '万';
			}

			return number;
		} catch (e) {
			return number;
		}
	}

	/**
	 * @description float 格式化，防止 js 精度丢失
	 */
	format_float(number) {
		number = parseFloat(number);
		if (isNaN(number)) return number;

		number = parseInt(number.toFixed(2) * 100);

		return number / 100;
	}

	/**
	 * @description float 格式化，防止 js 精度丢失
	 */
	format_int(number) {
		number = parseFloat(number);
		if (isNaN(number)) return number;

		number = parseInt(number.toFixed(0));

		return number;
	}

	/**
	 * @description 全球唯一 guid
	 */
	guid() {
		return (this.__s4() + this.__s4() + "-" + this.__s4() + "-" + this.__s4() + "-" + this.__s4() + "-" + this
			.__s4() +
			this.__s4() + this.__s4());
	}
	__s4() {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	}

	/**
	 * @description 消息提示 toast
	 */
	msg(title, duration = 2500, mask = false, icon = 'none') {
		if (!title) return;
		if (typeof title !== 'string') title = JSON.stringify(title);

		uni.showToast({
			title,
			duration,
			mask,
			icon
		});
	}

	/**
	 * @description 消息提示 alert
	 */
	alert(content, callback, bool) {
		if (typeof content !== 'string') content = JSON.stringify(content);
		uni.showModal({
			title: '提示',
			content: content,
			showCancel: !bool,
			success(res) {
				if (res.confirm) {
					if (typeof callback === 'function') {
						callback(true);
					}

				} else if (res.cancel) {
					callback(false);
				}
			}
		})
	}

	/**
	 * @description 获取路径参数
	 */
	get_params(data) {
		let params = '';
		if (typeof data === 'object') {
			for (let _ in data) {
				params += '&' + encodeURIComponent(_) + '=' + encodeURIComponent(data[_]);
			}
			params = '?' + params.slice(1);
		} else if (typeof data === 'string') {
			if (data.indexOf('?') != -1) params = data;
			else params = '?' + data;
		} else {
			params = data;
		}

		return params;
	}

	/**
	 * @param {Object} url路径
	 * @description 获取路径参数对象
	 */
	request(url) {
		var href = decodeURIComponent(url || location.href).split('#')[0];
		if (href.indexOf('?') == -1) return {};

		var params = href.split('?')[1];
		if (params === "") return {};

		params = params || '';
		var obj = {};

		if (params.indexOf('&') <= -1) {
			obj[params.split('=')[0]] = params.split('=')[1];
			return obj;
		}

		var arr = params.split('&'),
			len = arr.length,
			i = 0;

		for (i = 0; i < len; i++) {
			if (arr[i] != "") {
				obj[arr[i].split('=')[0]] = arr[i].split('=')[1];
			}
		}

		return obj;
	}
	/*
	  用正则表达式来检查字符串是否符合 URL 编码的格式
	*/
	isValidURLEncoding(str) {
		var urlregex = new RegExp(
			"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$"
		);
		return urlregex.test(str);
	}

	/** 
	 * @description js 判断对象是否为空 
	 * */

	isEmpty(obj) {
		if (JSON.stringify(obj) == "{}") {
			return true;
		}
		return false;
	}

	/**
	 * @description 去除两端空格
	 * */
	trim(str) {
		return str.replace(/\s+/g, "");
	}

	/**
	 * @description 注册当前环境
	 * */
	register_env(callback) {
		uni.getSystemInfo({
			success(sis) {
				let env = {
					platform: ''
				};

				// #ifdef MP-WEIXIN || MP-QQ || MP-BAIDU || MP-KUAISHOU
				if (uni.canIUse('getAccountInfoSync')) {
					{
						const accountInfo = uni.getAccountInfoSync();
						if (accountInfo && accountInfo.miniProgram) {
							env.appid = accountInfo.miniProgram.appId;
						}
					}
				}
				// #endif

				env.brand = sis.brand;
				env.language = sis.language;
				env.model = sis.model;
				env.platform = sis.platform;
				env.screenHeight = sis.screenHeight;
				env.screenWidth = sis.screenWidth;
				env.statusBarHeight = sis.statusBarHeight;
				env.system = sis.system;
				env.version = sis.version;
				env.windowHeight = sis.windowHeight;
				env.windowWidth = sis.windowWidth;
				env.pixelRatio = sis.pixelRatio;
				env.pixelRatio = sis.pixelRatio;
				env.mobileType = sis.platform;
				env.is_mp = false;
				env.is_wx = false;
				env.is_h5 = false;
				env.is_app = false;

				// #ifdef MP-WEIXIN
				env.platform = "weixin";
				env.platform_name = "微信";
				env.is_mp = true;
				env.is_wx = true;
				// #endif
				// #ifdef MP-QQ
				env.platform = "qq";
				env.platform_name = "QQ";
				env.is_mp = true;
				env.app_name = sis.AppPlatform;
				// #endif
				// #ifdef MP-ALIPAY
				env.platform = "alipay";
				env.platform_name = "支付宝";
				env.is_mp = true;
				env.app_name = sis.app;
				// #endif
				// #ifdef MP-BAIDU
				env.platform = "baidu";
				env.platform_name = "百度";
				env.is_mp = true;
				env.app_name = sis.host;
				// #endif
				// #ifdef MP-TOUTIAO
				env.platform = "toutiao";
				env.platform_name = "头条";
				env.is_mp = true;
				env.app_name = sis.appName;
				// #endif					
				// #ifdef MP-360
				env.platform = "360";
				env.platform_name = "360";
				env.is_h5 = true;
				env.app_name = "360小程序";
				// #endif
				// #ifdef H5
				env.platform = "h5";
				env.platform_name = "h5";
				env.is_h5 = true;
				// #endif
				// #ifdef H5-WEIXIN
				env.platform = "h5Weixin";
				env.platform_name = "微信公众号";
				env.is_h5 = true;
				env.is_wx = true;
				// #endif
				// #ifdef APP || APP-NVUE
				env.platform = "app";
				env.platform_name = "app";
				env.is_app = true;
				env.runtime = {};
				for (let key in plus.runtime) {
					if (typeof plus.runtime[key] === 'function') continue;
					env.runtime[key] = plus.runtime[key];
				}
				if (plus.runtime.isApplicationExist({
						pname: 'com.tencent.mm',
						action: 'weixin://'
					})) {
					console.log("微信应用已安装");
				} else {
					console.log("微信应用未安装");
				}
				env.os = {};
				for (let key in plus.os) {
					if (typeof plus.os[key] === 'function') continue;
					env.os[key] = plus.os[key].toLowerCase();
				}
				// #endif

				env.platform_icon = "icon" + env.platform;
				env.sis = sis;

				uni.getNetworkType({
					success(res) {
						console.log(res.networkType);
						env.networkType = res.networkType
					},
					complete() {
						console.log('set storage env', env);

						uni.setStorage({
							key: '__env',
							data: env
						})

						if (typeof callback === 'function') {
							callback(env);
						}
					}
				});
			}
		});
	}

	/**
	 * @description 运行环境
	 * */
	get_env(callback) {
		// return uni.getStorageSync('env');
		uni.getStorage({
			key: '__env',
			success(res) {
				if (typeof callback === 'function') {
					callback(res.data || {});
				}
			}
		})
	}

	dom(a, b) {
		if (arguments.length === 1 && typeof arguments[0] == 'string') {
			if (document.querySelector) {
				return document.querySelector(arguments[0])
			}
		} else if (arguments.length === 2) {
			if (typeof a === 'string')
				a = this.dom(a);
			if (a.querySelector) {
				return a.querySelector(b)
			}
		}
		return a
	}

	domAll(a, b) {
		if (arguments.length === 1 && typeof arguments[0] == 'string') {
			if (document.querySelectorAll) {
				return document.querySelectorAll(arguments[0])
			}
		} else if (arguments.length === 2) {
			if (typeof a === 'string')
				a = this.dom(a);
			if (a.querySelectorAll) {
				return a.querySelectorAll(b)
			}
		}
		return a
	}

	/**
	 * @description json 数组分组
	 * */
	fomtJsonGroup(arr) {
		var map = {},
			dest = [];
		for (var i = 0; i < arr.length; i++) {
			var ai = arr[i];
			if (!map[ai.type]) {
				dest.push({
					_id: ai._id,
					type: ai.type,
					tasktype: ai.tasktype,
					title: ai.title,
					subtitle: ai.subtitle,
					duration: ai.duration,
					totalhours: ai.totalhours,
					workhours: ai.workhours,
					estimatedhours: ai.estimatedhours,
					edate: ai.edate,
					ratio: ai.ratio,
					color: ai.color,
					children: [ai]
				});
				map[ai.type] = ai;
			} else {
				for (var j = 0; j < dest.length; j++) {
					var dj = dest[j];
					if (dj.type == ai.type) {
						dj.children.push(ai);
						break;
					}
				}
			}
		}
		console.log(dest);
		return dest;
	}
	/**
	 * @description 打印 info 日志
	 * */
	info(msg) {
		console.info(msg)
	}

	/**
	 * @description 当前页面数组
	 * */
	pages() {
		return getCurrentPages();
	}

	/**
	 * @description 返回上一级页面|跳转首页
	 * */
	back(bool) {
		console.log("后退");
		console.log(getCurrentPages())
		if (getCurrentPages().length > 1) {
			console.log("后退1");
			let pages = getCurrentPages(); // 当前页面        
			let beforePage = pages[pages.length - 2]; // 上一页   
			uni.navigateBack({
				success: function() {
					if (bool) {
						beforePage.$vm.reFresh();
					}
					console.log("返回成功!");
				}
			})
			return
		}
		this.tohome();
	}

	/**
	 * @description 指定元素选择器 offset
	 */
	offset(selector, callback) {
		let query = uni.createSelectorQuery().select(selector);
		// console.log('offset query', query);
		if (typeof callback === 'function') {
			query.boundingClientRect((res) => {
				callback(res);
			});
		}
	}

	/**
	 * @description 超时
	 */
	timerout(callback, timer = 1000) {
		let _timer = setTimeout(() => {
			if (typeof callback === 'function') {
				callback();
			}
			clearTimeout(_timer);
		}, timer);
	}

	/**
	 * @description 跳转登录页
	 */
	tologin(redirect) {
		if (redirect) {
			uni.redirectTo({
				url: $config.route.login
			});
			return;
		}

		uni.navigateTo({
			url: $config.route.login
		});
	}
	/**
	 * @description 跳转首页
	 */
	tohome() {
		uni.navigateTo({
			url: $config.route.home
		});
	}
	/**
	 * @description 跳转启动页
	 */
	tolaunch() {
		uni.redirectTo({
			url: $config.route.launch
		});
	}
	/**
	 * @description 跳转授权页
	 */
	toauth() {
		uni.navigateTo({
			url: $config.route.auth
		});
	}
	/**
	 * @description 跳转客服，微信客服
	 */
	tochat(url) {
		let corpid = $config.WeComId;
		// #ifdef APP-PLUS
		console.log("APP-PLUS");
		let sweixin = null
		plus.share.getServices(res => {
			sweixin = res.find(i => i.id === 'weixin')
			if (sweixin) {
				sweixin.openCustomerServiceChat({
					corpid: corpid,
					url: url,
				}, suc => {
					console.log("success", JSON.stringify(res))
				}, err => {
					console.log("error", JSON.stringify(err))
				})
			} else {
				console.log(res);
				plus.nativeUI.alert('当前环境不支持微信操作!');
			}
		}, function() {
			uni.showToast({
				title: "获取服务失败，不支持该操作。" + JSON.stringify(e),
				icon: 'error'
			})
		})
		// #endif
		// #ifdef MP-WEIXIN
		//--微信端调起企业微信
		console.log("mp-weixin");
		try {
			wx.openCustomerServiceChat({
				extInfo: {
					url: url
				},
				corpId: corpid,
				success(res) {
					console.log("success", JSON.stringify(res))
				},
				fail(res) {
					console.log(res);
					uni.showToast({
						title: "获取服务失败，不支持该操作。" + JSON.stringify(res.errMsg),
						icon: 'error'
					})
				}
			})
		} catch (error) {
			uni.showToast({
				title: "请更新至微信最新版本",
				icon: 'error'
			})
		}
		// #endif
	}

	/**
	 * @description 跳转订单列表页
	 */
	toorder() {
		uni.redirectTo({
			url: $config.route.order
		});
	}
	/**
	 * @description 查看协议
	 */
	toProtocol(params) {
		uni.navigateTo({
			url: `/pages/views/protocol` + this.get_params(params)
		});
	}
	/**
	 * @description 跳转统一支付页
	 */
	topay(params) {
		console.log(params);
		params.money = params.money || 0;
		params.type = params.type || 'navigate';

		if (params.type == 'redirect') {
			uni.redirectTo({
				url: $config.route.pay + this.get_params(params)
			});
			return;
		}

		uni.navigateTo({
			url: $config.route.pay + this.get_params(params)
		});
	}
	/**
	 * @description 跳转搜索页
	 */
	tosearch() {
		uni.reLaunch({
			url: $config.route.search
		});
	}
	/**
	 * @description 跳转搜索结果页
	 */
	tosearchlist(params) {
		if (params._type == 'redirect') {
			uni.redirectTo({
				url: $config.route.searchlist + this.get_params(params)
			});
			return;
		}
		uni.navigateTo({
			url: $config.route.searchlist + this.get_params(params)
		});
	}
	/**
	 * @description 跳转产品详情页
	 */
	togoods(params) {
		console.log('togoods params', params);
		uni.navigateTo({
			url: $config.route.goods + this.get_params(params)
		});
	}
	/**
	 * @description 跳转产品列表页
	 */
	togoodslist(params) {
		uni.navigateTo({
			url: $config.route.goodslist + this.get_params(params)
		});
	}

	/**
	 * @description 跳转指定 url
	 */
	toPage(params) { //内部链接
		if (params._type == 'redirect') {
			uni.redirectTo({
				url: params.url
			});
			return;
		}
		uni.navigateTo({
			url: params.url
		});
	}
	/**
	 * @description 打开淘宝搜索页面
	 */
	openTaobao(url) {
		plus.runtime.openURL(url, function(res) {
			uni.showModal({
				content: "本机未检测到淘宝客户端，是否打开浏览器访问淘宝？",
				success: function(res) {
					if (res.confirm) {
						plus.runtime.openURL("https://s.taobao.com/search?q=uni-app")
					}
				}
			})
		});
	}
	/**
	 * @description 自定义状态栏高度
	 */
	navbarHeight() {
		const {
			platform,
			statusBarHeight
		} = uni.getSystemInfoSync();

		let height = statusBarHeight;
		height += 4;
		if (platform == 'android') {
			height += 4;
		}

		return height + 32 + 6;
	}

	/**
	 * @description 获取路径文件名称
	 */
	getFileName(path) {
		if (path.indexOf('/') === -1) return path;

		return path.split('/').reverse()[0];
	}

	/**
	 * @description 上传文件
	 */
	async uploadFile(url, path, progress) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: this.$config.baseUrl + '/api/upload.ashx', //接口地址								
				filePath: url,
				name: 'file',
				formData: {
					'date': this.$api.formatDate(new Date()),
					'fpath': "userAvatar",
					'fileId': ''
				},
				//--header暂不设置，后台无法接收数据
				// header: {
				// 	"Content-Type": "multipart/form-data"
				// 	//"token": uni.getStorageSync('token'),
				// },
				//请求token
				success: (uRes) => {
					console.log('uploadFile', uRes);
					let __uRes = JSON.parse(uRes.data);
					console.log(__uRes);
					__uRes.url = this.$config.baseUrl + __uRes.path;
					__uRes.type = _type || 'image/';
					__uRes.size = _size;
					return __uRes;
				},
				fail: (err) => {
					console.log('use-upload', err);
					reject(err);
				}
			})
		});
	}

	// 获取 uni-sec-check 安全内容检测响应消息
	getSecMessage(res) {
		switch (res.errCode) {
			case 'uni-sec-check-system-error':
				return '系统错误，操作失败';
			case 'uni-sec-check-risk-content':
				const type = res.type || '';
				if (typeof res.idx === 'number') {
					return `${type}[${res.idx++}]存在风险内容`;
				}
				return `${type}存在风险内容`;
			case 'uni-sec-check-invalid-file-type':
				return '错误的文件类型';
			case 'uni-sec-check-invalid-image-size':
				return '图片大小超出限制';
			case 'uni-sec-check-invoke-out-of-limit':
				return '调用过于频繁，稍后再试';
			default:
				return `${res.errCode} ${res.errMsg}`;
		}
	}

	formatLocation(longitude, latitude) {
		if (typeof longitude === 'string' && typeof latitude === 'string') {
			longitude = parseFloat(longitude)
			latitude = parseFloat(latitude)
		}

		longitude = longitude.toFixed(2)
		latitude = latitude.toFixed(2)

		return {
			longitude: longitude.toString().split('.'),
			latitude: latitude.toString().split('.')
		}
	}
	// 版本号比较
	compareVersion(curr, prev) {
		const prevs = prev.split('.');
		const currs = curr.split('.');
		let flag = false;
		let prevVal = 0;
		let currVal = 0;
		for (let i = 0; i < currs.length; i++) {
			prevVal = parseInt(prevs[i]);
			currVal = parseInt(currs[i]);
			if (prevVal > currVal) {
				break;
			}
			if (currVal > prevVal) {
				flag = true;
				break;
			}
		}
		return flag;
	}
	// 检测全面屏
	checkFullScreen() {
		let isFullScreen = false
		const rate = window.screen.height / window.screen.width;
		let limit = window.screen.height == window.screen.availHeight ? 1.8 : 1.65; // 临界判断值   
		// window.screen.height为屏幕高度
		// window.screen.availHeight 为浏览器 可用高度
		if (rate > limit) {
			isFullScreen = true;
		}
		return isFullScreen
	}
	// 微信内部浏览器
	isInternalWeixin() {
		// 测试阶段，默认为 true
		if ($config.debug) return true;
		return location.href.indexOf('code') !== -1 && navigator.userAgent.toLowerCase().match(
			/MicroMessenger/i);
	}

	// 获取当前 page
	getCurPage() {
		const pages = this.pages();
		const curPage = pages[pages.length - 1];

		return curPage;
	}
	// 获取当前 page 请求参数
	getCurPageParamObj() {
		return this.getCurPage().options;
	}
	// 获取当前 page 请求参数
	getCurPageParam(param, allowParams = []) {
		const page = this.getCurPage();

		const options = [];
		param = {
			...page.options,
			...param
		};
		for (let key in param) {
			if (allowParams.length && !allowParams.includes(key)) {
				continue;
			}
			options.push(`${key}=${param[key]}`);
		}
		return options.join('&');
	}
	// 获取当前 page 完整请求 url
	getCurPageFullUrl(param, allowParams = []) {
		const page = this.getCurPage();
		const options = this.getCurPageParam(param, allowParams);

		return `${page.route}?${options}`;
	}
	// 获取对应的设备类型
	os() {
		var ua = navigator.userAgent,
			isWindowsPhone = /(?:Windows Phone)/.test(ua),
			isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
			isAndroid = /(?:Android)/.test(ua),
			isFireFox = /(?:Firefox)/.test(ua),
			isChrome = /(?:Chrome|CriOS)/.test(ua),
			isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (
				isFireFox &&
				/(?:Tablet)/.test(ua)),
			isPhone = /(?:iPhone)/.test(ua) && !isTablet,
			isPc = !isPhone && !isAndroid && !isSymbian;

		return {
			isTablet: isTablet,
			isPhone: isPhone,
			isAndroid: isAndroid,
			isPc: isPc
		};
	}
	// pc 端
	ispc() {
		const {
			isPc
		} = this.os();
		return isPc;
	}

	overShare() {
		// 监听路由切换
		wx.onAppRoute(function(res) {
			let pages = getCurrentPages()
			let view = pages[pages.length - 1]
			if (view) {
				wx.showShareMenu({
					withShareTicket: true,
					menus: ['shareAppMessage', 'shareTimeline']
				})
			}
		})
	}
	showToast(tip) {
		wx.showToast({
			title: tip || '成功',
			icon: 'none',
			duration: 2000
		})
	}
	showModal(tip, callback) {
		wx.showModal({
			title: '提示',
			content: tip || '操作失败！',
			showCancel: false,
			success(res) {
				if (callback != undefined) {
					callback(res);
				}
			}
		})
	}
	showCancelModal(tip, callback) {
		wx.showModal({
			title: '提示',
			content: tip || '操作失败！',
			success(res) {
				callback(res)
			}
		})
	}
	showDiyModal(tip, btnTxt, callback) {
		wx.showModal({
			title: '提示',
			cancelText: btnTxt.cancelText,
			confirmText: btnTxt.confirmText,
			content: tip || '操作失败！',
			success(res) {
				callback(res)
			}
		})
	}
	//数组模糊查询
	onSearch(list, searchTxt) {
		list = list.filter(function(t) {
			return t.searchField.search(searchTxt) > -1 //search()或者indexOf()
		})
		return list;
	}
	openDocument(url) {
		console.log(url)
		wx.showLoading({
			title: '加载中...',
		})
		wx.downloadFile({
			url: url,
			success: function(res) {
				console.log("downloadFile", res)
				const filePath = res.tempFilePath
				wx.shareFileMessage({
					filePath: filePath,
					success(data) {
						console.log("转发成功", data)
					},
					fileName: 'asa',
					fail: console.error,
				})
				wx.openDocument({
					filePath: filePath,
					success: function(res) {
						console.log(res)
					},
					fail: function(res) {
						console.log(res)
					},
					complete: function(res) {
						wx.hideLoading()
					}
				})
			}
		})
	}
	//姓名加密
	nameSecret(name) {
		name = name.split('');
		var str = '';
		name.forEach(function(item, i) {
			if (i == (name.length - 1)) {
				str += '*';
			} else {
				str += item
			}
		})
		return str;
	}
	getNow(s) {
		return s < 10 ? '0' + s : s;
	}
	getDateDefault(type, n, mode) {
		//return new Date().getTime(); 
		var date = new Date();

		function getNow(s) {
			return s < 10 ? '0' + s : s;
		}
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
		let hours = date.getHours(); //小时 ,返回 Date 对象的小时 (0 ~ 23)
		let minutes = date.getMinutes(); //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
		let seconds = date.getSeconds(); //秒 ,返回 Date 对象的秒数 (0 ~ 59) 
		if (type === 'start') {
			year = year - 1;
		} else if (type === 'end') {
			//year = year + 10;
		}
		if (type === 'start' || type === 'end') {
			month = month > 9 ? month : '0' + month;
			day = day > 9 ? day : '0' + day;
			return `${year}-${month}-${day}`;
		} else if (type === 'time') {
			return year + "-" + getNow(month) + "-" + getNow(day) + " " + getNow(hours) + ":" + getNow(minutes) +
				":" + getNow(seconds);
		} else if (type === 'onlyTime') {
			return getNow(hours) + ":" + getNow(minutes);
		} else if (type === 'timeStr') {
			return year + "" + getNow(month) + "" + getNow(day) + "" + getNow(hours) + "" + getNow(minutes) + "" +
				getNow(seconds);
		} else if (type === 'specify' || type == 'specifyDate') {
			var tomDay = new Date();
			if (type == 'specifyDate') {
				tomDay = new Date(mode)
			}
			tomDay.setTime(tomDay.getTime() + n * 24 * 60 * 60 * 1000);
			return tomDay.getFullYear() + "-" + getNow(tomDay.getMonth() + 1) + "-" + getNow(tomDay.getDate());
		} else if (type === 'specifyTime' || type == 'specifyTime1') {
			var tomDay = new Date();
			if (type == 'specifyTime1') {
				tomDay = new Date(mode)
			}
			var min = tomDay.getMinutes();
			tomDay.setMinutes(min + n);
			return getNow(tomDay.getHours()) + ":" + getNow(tomDay.getMinutes());
		}
	}
	//自动获取显示时间格式
	getShowTime(type, time) {
		var showTime;
		var nowDate = this.getDateDefault('end');
		if (time.split(' ')[0] == nowDate) {
			showTime = this.date_RegularCalc(time, 'nowTime') + '前';
		} else {
			if (type == 'default') {
				showTime = time.substring(0, 16);
			} else if (type == 'noTime') {
				showTime = time.split(' ')[0];
			}
		}
		return showTime;
	}
	//计算时间差
	date_RegularCalc(start, end) {
		var showTime = '';
		var start_date = new Date(start.replace(/\-/g, "/")).getTime();
		if (end == 'nowTime') {
			var end_date = new Date().getTime();
		} else {
			console.log(end)
			var end_date = new Date(end.replace(/\-/g, "/")).getTime();
		}
		var calcTime = parseInt(end_date - start_date) / 1000;
		if (calcTime < 60) {
			if (calcTime < 0) {
				calcTime = 0;
			}
			showTime = parseInt(calcTime) + '秒';
		} else if (calcTime >= 60 && calcTime < 3600) {
			showTime = parseInt(calcTime / 60) + '分钟';
		} else if (calcTime >= 3600 && calcTime < 86400) {
			showTime = parseInt(calcTime / 60 / 60) + '小时';
		}
		return showTime;
	}
	//判断日期
	date_Regular(start, end) {
		var reg = false;
		var start_date = new Date(start.replace(/\-/g, "/")).getTime();
		var end_date = new Date(end.replace(/\-/g, "/")).getTime();
		if (parseInt(end_date - start_date) / 1000 / 60 / 60 / 24 < 0) {
			reg = false;
		} else {
			reg = true;
		}
		return reg;
	}
	// 比较日期
	compareDate(strDate1, strDate2) {
		// 将日期字符串转换为 Date 对象
		const date1 = new Date(strDate1);
		const date2 = new Date(strDate2);
		if (date1 > date2) {
			return true;
		} else {
			return false;
		}
	}
	//计算天数差
	date_difference(date1, date2) {
		var d1 = new Date(date1.replace(/\-/g, "/")).getTime();
		var d2 = new Date(date2.replace(/\-/g, "/")).getTime();
		var re = parseInt(d2 - d1) / 1000 / 60 / 60 / 24;
		re += 1;
		if (0 < re && (re < 1 || re == 1)) {
			re = 1;
		} else if (re > 1) {
			re = Math.round(re);
		}
		return re;
	}
	//*日期格式化，返回格式，yyyy-mm-dd
	formatDate(date) {
		const y = date.getFullYear()
		let m = date.getMonth() + 1
		m = m < 10 ? ('0' + m) : m
		let d = date.getDate()
		d = d < 10 ? ('0' + d) : d
		return y + '-' + m + '-' + d
	}
	// 计算当前日期的 dayCount 天
	GetDateStr(dayCount) {
		const dd = new Date()
		dd.setDate(dd.getDate() + dayCount) // 获取dayCount天后的日期
		const y = dd.getFullYear()
		const m = (dd.getMonth() + 1) < 10 ? '0' + (dd.getMonth() + 1) : (dd.getMonth() + 1) // 获取当前月份的日期，不足10补0
		const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
		return y + '-' + m + '-' + d
	}
	getSmallpic(fileID, size) {
		var url = this.globalData.baseUrl + '/admin/downloadfile.aspx?action=smallpic&height=' + size + '&fileID=' +
			fileID;
		return url;
	}
	uploadimg(data, callback) {
		// --图片上传
		console.log('图片上传', data)
		var that = this,
			i = data.i ? data.i : 0,
			success = data.success ? data.success : 0,
			fail = data.fail ? data.fail : 0;
		uni.uploadFile({
			url: data.url,
			filePath: data.path[i],
			name: 'file',
			formData: data.formData,
			success: (resp) => {
				success++;
				data.uploadData.push(JSON.parse(resp.data))
				//console.log(resp)
			},
			fail: (res) => {
				fail++;
				console.log('fail' + i + "fail:" + fail);
			},
			complete: () => {
				i++;
				if (i == data.path.length) { //图片上传完，停止调用
					//console.log('执行完毕');
					console.log('成功：' + success + "失败：" + fail);
					callback(data.uploadData);
				} else { //图片还没上传完，继续调用
					data.i = i;
					data.success = success;
					data.fail = fail;
					that.uploadimg(data, callback);
				}
			}
		})
	}
	//数组分解
	arrayResolve(n, arr) {
		let result = [];
		for (let i = 0; i < arr.length; i += n) {
			result.push(arr.slice(i, i + n));
		}
		return result
	}
	//数据分组
	dataGroup(arr, type) {
		var map = {},
			dest = [];
		for (var i = 0; i < arr.length; i++) {
			var ai = arr[i];
			if (!map[ai.类型]) {
				dest.push({
					itemId: ai.类型,
					clients: [ai]
				});
				map[ai.类型] = ai;
			} else {
				for (var j = 0; j < dest.length; j++) {
					var dj = dest[j];
					if (dj.itemId == ai.类型) {
						dj.clients.push(ai);
						break;
					}
				}
			}
		}
		return dest;
	}
	preview(currentUrl, imgArr) {
		wx.previewImage({
			current: currentUrl, // 当前显示图片的http链接
			urls: imgArr, // 需要预览的图片http链接列表
		})
	}
	//金额正则
	checkmoney(money) {
		var reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
		if (parseFloat(money) == 0) {
			return false;
		}
		if (reg.test(money)) {
			return true;
		}
		return false;
	}
	clearNoNum(amount) {
		amount = amount.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
		amount = amount.replace(/^\./g, ""); //验证第一个字符是数字而不是字符
		amount = amount.replace(/\.{2,}/g, "."); //只保留第一个.清除多余的
		amount = amount.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
		amount = amount.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
		return amount;
	}
	getImageInfo(src, callback) {
		return new Promise((resolve, reject) => {
			wx.getImageInfo({
				src: src,
				success: (result) => {
					if (callback != undefined) {
						callback(result)
						resolve(); // 返回给await
					}
				}
			})
		})
	}
	insertStr(soure, start, newStr) {
		return soure.slice(0, start) + newStr + soure.slice(start);
	}
	delStr(soure, start, end) {
		return soure.slice(0, start) + soure.slice(end);
	}
	//文件大小显示
	fileSizeConver(limit) {
		limit = Number(limit);
		var size = "";
		if (limit < 0.1 * 1024) { //如果小于0.1KB转化成B
			size = limit.toFixed(2) + "B";
		} else if (limit < 0.1 * 1024 * 1024) { //如果小于0.1MB转化成KB
			size = (limit / 1024).toFixed(2) + "KB";
		} else if (limit < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
			size = (limit / (1024 * 1024)).toFixed(2) + "MB";
		} else { //其他转化成GB
			size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
		}
		var sizestr = size + "";
		var len = sizestr.indexOf("\.");
		var dec = sizestr.substr(len + 1, 2);
		if (dec == "00") { //当小数点后为00时 去掉小数部分
			return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
		}
		return sizestr;
	}
	digitUppercase(n) {
		var fraction = ['角', '分'];
		var digit = [
			'零', '壹', '贰', '叁', '肆',
			'伍', '陆', '柒', '捌', '玖'
		];
		var unit = [
			['元', '万', '亿'],
			['', '拾', '佰', '仟']
		];
		var head = n < 0 ? '欠' : '';
		n = Math.abs(n);
		var s = '';
		for (var i = 0; i < fraction.length; i++) {
			s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
		}
		s = s || '整';
		n = Math.floor(n);
		for (var i = 0; i < unit[0].length && n > 0; i++) {
			var p = '';
			for (var j = 0; j < unit[1].length && n > 0; j++) {
				p = digit[n % 10] + unit[1][j] + p;
				n = Math.floor(n / 10);
			}
			s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
		}
		return head + s.replace(/(零.)*零元/, '元')
			.replace(/(零.)+/g, '零')
			.replace(/^整$/, '零元整');
	}
	//将用户输入内容中的尖括号、引号等进行转义//@//- -特殊空格
	html_encode(str) {
		var s = "";
		if (str.length == 0) return "";
		s = str.replace(/\n/g, "<br>");
		s = s.replace(/</g, "&lt;");
		s = s.replace(/>/g, "&gt;");
		s = s.replace(/ /g, "&nbsp;");
		s = s.replace(/\'/g, "&#39;");
		s = s.replace(/\"/g, "&quot;");
		s = s.replace(/\//g, '&#x2F;')
		return s;
	}
	html_decode(str) {
		var s = "";
		if (str.length == 0) return "";
		s = str.replace(/<br>/g, "\n");
		s = s.replace(/&lt;/g, "<");
		s = s.replace(/&gt;/g, ">");
		s = s.replace(/&nbsp;/g, " ");
		s = s.replace(/&#39;/g, "\'");
		s = s.replace(/&quot;/g, "\"");
		s = s.replace(/&#x2F;/g, '\/')
		return s;
	}
	getTypeIcon(type) {
		var src = '',
			_base = $config.baseUrl;
		switch (type) {
			case '日常':
				return _base + '/api/resources/images/F_daily.png';
				break;
			case '执行':
				return _base + '/api/resources/images/F_work.png';
				break;
			case '商机':
				return _base + '/api/resources/images/F_business.png';
				break;
			case '月办':
				return _base + '/api/resources/images/F_monthly.png';
				break;
			case '工单':
				return _base + '/api/resources/images/W_order.png';
				break;
			default:
				return _base + '/api/resources/images/F_business.png';
				break;
		}
	}
	// 检查是否不再显示广告
	shouldShowAd() {
		const dontShowAgain = uni.getStorageSync('dontShowAgain');
		if (dontShowAgain) {
			return false;
		}

		// 检查当天是否已经显示过广告
		const lastAdDate = uni.getStorageSync('lastAdDate');
		const today = new Date().toLocaleDateString();
		if (lastAdDate === today) {
			return false;
		}

		// 其他条件判断，例如用户是否登录、网络连接状态等

		// 如果需要显示广告，则更新上次显示时间
		uni.setStorageSync('lastAdDate', today);
		return true;
	}
}

export default new Util()